import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait

# 1. 打开浏览器（注意：ChromeDriver若配置环境变量，可省略executable_path）
driver = webdriver.Chrome(executable_path='chromedriver.exe')  # 若报错，可替换为 driver = webdriver.Chrome()
driver.maximize_window()

# 2. 先访问淘宝域名（必须先打开目标网站，否则无法添加Cookie）
driver.get("https://www.taobao.com")
time.sleep(2)  # 等待页面加载

# 3. 你的完整Cookie字符串（从浏览器复制的）
cookie_str = "mtop_partitioned_detect=1; _m_h5_tk=dfaedcdea0f8beb583fc7db1c8234e22_1762024360783; _m_h5_tk_enc=39d2730d0867ca0be8502402e7890ef6; t=8ff9db7e621ba73757fd6f1bf69794fe; _tb_token_=ee335833f353d; cna=USmNIY/yFgMCAXjrSOLriy4G; thw=cn; arms_uid=d6c409a2-cace-4889-81fd-02aef8ee7bb2; sca=fc6cb8ab; xlly_s=1; 3PcFlag=1762016097162; _hvn_lgc_=0; csg=861714fb; lgc=tb479271223; cancelledSubSites=empty; dnk=tb479271223; tracknick=tb479271223; _l_g_=Ug%3D%3D; sg=33d; _nk_=tb479271223; uc1=cookie14=UoYY4dkasW9rDA%3D%3D&cookie15=UIHiLt3xD8xYTw%3D%3D&existShop=false&pas=0&cookie21=U%2BGCWk%2F7pY%2FF&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D; sn=; existShop=MTc2MjAxNjExMg%3D%3D; _cc_=VT5L2FSpdA%3D%3D; aui=4008867653; havana_lgc_exp=1793120114939; sdkSilent=1762044914939; havana_sdkSilent=1762044914939; isg=BNPTD4YfvvwtMHIoTnNkGJaZYlf9iGdKzb7YfYXw6PIpBPGmD1nbmrsePnVqkL9C; tfstk=geZKQCYQE1f3rhAep7bGrRzEUUXieN2etWyXqbcHP5FTh-RnPbbUw4Fu_4ZnxJV9LlFvqHfF88t-q01ciij0LJmrVsAmA7JwTYMSNg0IOdiEEIsx8hs0LJoypQ605ijJ8Ay6AUG7NcGsUxnSdHMWfOH-HbiSO4O65xGsN0NSOhisEY8WReG5BRGZF0G7N06tffkSVbNSVjh2pbvIw3UEX7h3rijePUZtp2hJ4f--Gltm8jwI63sTXvdEGJG9V3hjQb2bBJfp0RmUjSH0tGtLMJabNrN1XH3aRRE-uuRCC0g7Sr0LW6t-skD-l0g9F3wtAfuSLmsX6Az_KzZU9LKSLkqmyjuOF3uofo0blWpP3RiIF7u4qs-EO8w40rmA2hiKPg7bmoU-N2hxEe6OBU8rRAYRchxtJrZikAhcIFYyzVDZBjXOBU8rRAktiOjMzUuiQ"

# 4. 关键：拆分Cookie为单个键值对，逐个添加（解决核心错误）
# 按 "; " 分割Cookie字符串，得到每个独立的 "name=value"
cookies_list = cookie_str.split("; ")
for cookie in cookies_list:
    # 按第一个 "=" 分割（避免value中包含"="导致拆分错误）
    name, value = cookie.split("=", 1)
    # 构造Selenium要求的Cookie格式，显式指定域名（解决跨域问题）
    cookie_dict = {
        "name": name,
        "value": value,
        "domain": ".taobao.com"  # 淘宝的通用域名，必须带前面的点
    }
    try:
        driver.add_cookie(cookie_dict)
        print(f"成功添加Cookie：{name}")
    except Exception as e:
        # 忽略个别无效Cookie（如临时Cookie），不影响整体登录
        print(f"添加Cookie {name} 失败：{str(e)[:50]}")  # 只显示前50字符，避免输出过长

# 5. 刷新页面，完成免登录
driver.refresh()
print("\n已尝试刷新登录，可观察页面是否显示用户名（如 tb998680071）")

# 6. 验证登录状态（可选：打印当前Cookie，确认添加成功）
cookies = driver.get_cookies()
print("\n当前浏览器中的Cookie名称列表：")
for co in cookies:
    print(co['name'])

# 停留10秒，观察登录结果
time.sleep(3)